import ReactDOM from 'react-dom'
import { useState, useReducer } from 'react'

// 解释：一个action对应一个功能
//  比如：计数器加1，这是一个功能，这也是一个action
//        计数器减1，这又是一个功能，这也是一个action
type ActionType = { type: 'increment' } | { type: 'decrement' }

const reducer = (state: number, action: ActionType) => {
  switch (action.type) {
    case 'increment':
      return state + 1
    case 'decrement':
      return state - 1
    default:
      return state
  }
}

const Counter = () => {
  // const [count, setCount] = useState(0)
  // const addClick = () => {
  //   setCount(count + 1)
  // }
  // const subClick = () => {
  //   setCount(count - 1)
  // }

  // 使用reducer
  const [state, dispatch] = useReducer(reducer, 0)
  const addClick = () => {
    dispatch({ type: 'increment' })
  }
  const subClick = () => {
    dispatch({ type: 'decrement' })
  }
  return (
    <div>
      <h1>{state}</h1>
      <button onClick={addClick}>加1</button>
      <button onClick={subClick}>减1</button>
    </div>
  )
}

ReactDOM.render(<Counter />, document.getElementById('root'))
